<template>
  <BasicModal
    v-bind="$attrs"
    destroyOnClose
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="70%"
    :minHeight="300"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <div class="ml-1">
      <BasicForm @register="registerForm" />
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, nextTick } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { buttonsSchema } from './btn.data';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { cloneDeep } from 'lodash-es';

  import { BasicModal, useModalInner } from '/@/components/Modal';

  export default defineComponent({
    name: 'ButtonConfigModal',
    components: {
      BasicModal,
      BasicForm,
    },
    props: ['classify'],
    emits: ['success', 'register'],
    setup(props, { emit }) {
      const update = ref<any>({
        isUpdate: false,
      });
      const { createMessage } = useMessage();

      const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
        rowProps: { gutter: 16 },
        labelWidth: 110,
        baseColProps: { lg: 11, md: 8 },
        schemas: buttonsSchema(props.classify),
        showActionButtonGroup: false,
      });
      const [registerDrawer, { setModalProps, closeModal }] = useModalInner(async (data) => {
        console.log(data);

        resetFields();
        setModalProps({ confirmLoading: false });

        if (!!data?.isUpdate) {
          setFieldsValue({
            ...data?.record,
          });
          nextTick(() => {
            if (data?.record.modelClassify) {
              //  需要初始化重置
              setFieldsValue({ dataModelId: data?.record.dataModelId });
            }
          });
        }

        update.value = {
          isUpdate: !!data?.isUpdate,
          index: data?.record?.index,
          record: cloneDeep(data?.record || {}),
        };
      });

      const getTitle = computed(() => (!unref(update).isUpdate ? '新增' : '编辑'));

      async function handleSubmit() {
        try {
          const values = await validate();
          setModalProps({ confirmLoading: true });
          const params = Object.assign(unref(update).record, values);
          params.params = params.params || '{}';
          createMessage.success('操作成功');
          closeModal();
          update.value.record = params;
          emit('success', unref(update));
          return;
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }
      function handleCancel() {
        update.value.isUpdate && emit('success', unref(update));
      }
      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
        handleCancel,
      };
    },
  });
</script>
